#!/usr/bin/env sh

# 选择或输入 PHP 镜像
PHP_Image_Selection()
{
  while [ -z "${PHP_IMAGE}" ]; do
    Echo_Blue "选择 PHP 镜像(${#PHP_IMAGES[*]}):"

    # for image in ${PHP_IMAGES[*]}
    for ((i=0;i<${#PHP_IMAGES[*]};i++))
    do
      echo "${i}) ${PHP_IMAGES[i]}"
    done

    read -p "请选择镜像序号, 或输入镜像名称: " PHP_IMAGE
    echo

    if [[ ${PHP_IMAGE} =~ ^[0-9]+$ ]]; then
      PHP_IMAGE=${PHP_IMAGES[${PHP_IMAGE}]}
    fi
  done

  # 配置镜像
  PHP_Config
}

# PHP 配置
PHP_Config()
{
  Echo_Green "PHP 配置:"
  echo "PHP_IMAGE=${PHP_IMAGE}"

  # 包名:版本号
  image=${PHP_IMAGE%%-*}
  repository=${image%:*}
  version=${image#*:}

  # 资源路径
  PHP_PATH=${DATA_PATH}/${repository}/${version}

  # 镜像构建脚本 PHP_BUILD
  while [[ -z "${PHP_BUILD}" || ! -d ${PHP_BUILD} ]]
  do
    if [ -z "${PHP_BUILD}" ]; then
      CACHE="${DATA_PATH}/docker/dockerfiles/php/${PHP_IMAGE#*:}"
      read -p "镜像构建脚本(default=${CACHE}): " PHP_BUILD
    else
      echo "PHP_BUILD=${PHP_BUILD}"
    fi
    if [ -z "${PHP_BUILD}" ]; then
      PHP_BUILD=${CACHE}
    fi
    # 校验镜像脚本目录是否存在
    if [ ! -d ${PHP_BUILD} ]; then
      Echo_Red "镜像构建脚本不存在！"
      # 选择已有的镜像脚本
      dockerfiles=(`ls -r ${DATA_PATH}/docker/dockerfiles/php`)
      dockerfile=
      while [ -z "${dockerfile}" ]; do
        echo "选择已有的构建脚本:"
        for ((i=0;i<${#dockerfiles[*]};i++))
        do
          echo "${i}) ${dockerfiles[i]}"
        done

        read -p "请选择: " dockerfile
        if [[ ${dockerfile} =~ ^[0-9]+$ ]]; then
          dockerfile=${dockerfiles[${dockerfile}]}
        fi
      done
      PHP_BUILD="${DATA_PATH}/docker/dockerfiles/php/${dockerfile}"
    fi
  done

  # 确认并保存配置
  PHP_Config_Confirm
}

# 确认配置
PHP_Config_Confirm()
{
  confirm="y"
  read -p "确认配置Y/n: " confirm
  if [[ -z "${confirm}" || "${confirm}" == "y" ]]; then
    # 保存全局安装配置
    PHP_Config_Update

    # 更新镜像构建脚本
    sed -i -e "s|PHP_IMAGE|${PHP_IMAGE}|g;" ${PHP_BUILD}/Dockerfile

    Echo_Green "PHP 配置已保存！"
    echo
  else
    # 重置
    PHP_IMAGE=
    PHP_BUILD=
    PHP_PATH=
    echo
    PHP_Image_Selection
  fi
}

# 更新数据库配置
PHP_Config_Update()
{
  # install.conf
  sed -i -e "s|PHP_IMAGE=.*|PHP_IMAGE=${PHP_IMAGE}|g;" ${INSTALL_CONF}
  sed -i -e "s|PHP_BUILD=.*|PHP_BUILD=${PHP_BUILD}|g;" ${INSTALL_CONF}
  sed -i -e "s|PHP_PATH=.*|PHP_PATH=${PHP_PATH}|g;" ${INSTALL_CONF}

  # docker-compose.yml
  sed -i -e "s|PHP_IMAGE|${PHP_IMAGE}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|PHP_BUILD|${PHP_BUILD}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|PHP_PATH|${PHP_PATH}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|TCP_PORT|${TCP_PORT}|g;" ${DOCKER_COMPOSE_YML}
  sed -i -e "s|MQTT_PORT|${MQTT_PORT}|g;" ${DOCKER_COMPOSE_YML}
  
  # Dockerfile
}